import { defineStore } from 'pinia'
import type { IAccount } from '@/types'
import {
  accountLoginRequest,
  getUserInfoById,
  getUserMenusByLoginUser
} from '@/service/login/login'
import { localCache } from '@/utils/cache'
import { LOGIN_TOKEN } from '@/global/constants'
import router from '@/router'
import type { RouteRecordRaw } from 'vue-router'
import { mapMenusToRoutes } from '@/utils/map-menus'

interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
}

const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    token: localCache.getCache(LOGIN_TOKEN) ?? '',
    userInfo: localCache.getCache('userInfo') ?? '',
    userMenus: localCache.getCache('userMenus') ?? ''
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      // 开始账号登录
      const loginResult = await accountLoginRequest(account)
      // console.log(loginResult)
      this.token = loginResult.token

      // 2.进行本地缓存
      localCache.setCache(LOGIN_TOKEN, this.token)

      // 获取当前登录用户信息
      const userInfoResult = await getUserInfoById()
      // console.log(userInfoResult.user)
      this.userInfo = userInfoResult
      // 获取当前用户对应的菜单数据
      const userMenus = await getUserMenusByLoginUser()
      // console.log(userMenus.data)
      this.userMenus = userMenus.data

      localCache.setCache('userInfo', userInfoResult.user)
      localCache.setCache('userMenus', userMenus.data)
      // 开始动态注册路由
      const localRoutes: RouteRecordRaw[] = []
      // 读取所有配置文件
      const files = import.meta.glob('../../router/**/*.ts')
      console.log(files)
      for (const key in files) {
        console.log(files[key])
      }
      // 5.页面跳转(main页面)
      await router.push('/main')
    },
    loadLocalCacheAction() {
      // 1.用户进行刷新默认加载数据
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache('userInfo')
      const userMenus = localCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 2.动态添加路由
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    }
  }
})

// 导航守卫
router.beforeEach((to) => {
  // 只有登录成功(有token值 才能进入main页面)
  const token = localCache.getCache(LOGIN_TOKEN)
  if (to.path.startsWith('/main') && !token) {
    return '/login'
  }
})

export default useLoginStore
